package com.hdu.hot100.tree;

import jdk.nashorn.internal.ir.Terminal;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class lc437 {


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        static Map<Long, Integer> preSum2count = new HashMap<>();
        static int ans = 0;
        public int pathSum(TreeNode root, int targetSum) {
            preSum2count.clear();
            preSum2count.put(0L, 1);
            ans = 0;
            f(root, 0, targetSum);
            return ans;
        }

        void f(TreeNode root, long curSum, int targetSum)
        {
            if (root == null)
            {
                return;
            }
            ans += preSum2count.getOrDefault(curSum + root.val - targetSum, 0);
            preSum2count.put(curSum + root.val, preSum2count.getOrDefault(curSum + root.val, 0) + 1);
            f(root.left, curSum + root.val, targetSum);
            f(root.right, curSum + root.val, targetSum);
            preSum2count.put(curSum + root.val, preSum2count.get(curSum + root.val) - 1);
            preSum2count.put(curSum + root.val, preSum2count.getOrDefault(curSum + root.val, 0) - 1);
        }
    }
}
